package cn.e4j.modular.crm.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.LangUtils;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.mapper.GwaeTMapper;
import cn.e4j.modular.crm.mapper.GwakTMapper;
import cn.e4j.modular.crm.mapper.GwamTMapper;
import cn.e4j.modular.crm.service.impl.GwdbTServiceImpl;
import cn.e4j.modular.utils.CrmExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 渠道价格维护管理
 * Created by shixc on 2019-2-1.
 */
@Controller
@RequestMapping("/crm/gwdc002")
public class Gwdc002Controller extends BaseController {

    @Autowired
    private GwdbTServiceImpl gwdc002Service;

    @Autowired
    private GwakTMapper gwakTMapper;

    @Autowired
    private GwaeTMapper gwaeTMapper;

    @Autowired
    private GwamTMapper gwamTMapper;

    /**
     * 跳转渠道价格管理页面
     */
    @RequiresPermissions("crm:gwdc002:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/crm/gwdc002.html";
    }

    /**
     * 查询渠道价格信息列表
     */
    @RequestMapping("/getList")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData getList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWDBENT", shiroUser.getDBC());
        List<Map<String, Object>> result = gwdc002Service.getListData(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 获取新增申请单号
     */
    @RequestMapping("/getGwdb001")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData getGwdb001(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto addDataDto = gwdc002Service.getGwdb001(inDto);
        return new SuccessResponseData(addDataDto);
    }

    /**
     * 新增
     */
    @RequestMapping("/addData")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData addData(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdbT> gwdbTList = inDto.getReqList(GwdbT.class);
        Dto dto = gwdc002Service.addData(gwdbTList);
        if (dto.getAppCode() == 400) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDC.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDC.getMessage());
        }
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/del")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData del(GwdbT gwdbT) {
        gwdc002Service.delete(gwdbT);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除数据
     */
    @RequestMapping("/deleteDataBatch")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData deleteDataBatch(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdbT> gwdbTList = inDto.getReqList(GwdbT.class);
        gwdc002Service.delDataBatch(gwdbTList);
        return SUCCESS_TIP;
    }

    /**
     * 批量审核数据
     */
    @RequestMapping("/check")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData check(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdbT> gwdbTList = inDto.getReqList(GwdbT.class);
        gwdc002Service.check(gwdbTList);
        return SUCCESS_TIP;
    }

    /**
     * 批量取消审核数据
     */
    @RequestMapping("/unCheck")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData unCheck(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdbT> gwdbTList = inDto.getReqList(GwdbT.class);
        gwdc002Service.unCheck(gwdbTList);
        return SUCCESS_TIP;
    }

    /**
     * 查询商品信息列表
     */
    @RequestMapping("/listGwdb")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData listGwdb(@DtoParam DtoWapper dtoWapper) {
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWDBENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> result = gwdc002Service.listGwdb(inDto);
        return ResponseData.success(result);
    }

    /**
     * 修改
     */
    @RequestMapping("/editData")
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData editData(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdbT> gwdbTList = inDto.getReqList(GwdbT.class);
        Dto dto = gwdc002Service.editData(gwdbTList);
        if (dto.getAppCode() == 400) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDC.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDC.getMessage());
        }
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/exportsData", method = RequestMethod.GET)
    @RequiresPermissions("crm:gwdc002:init")
    public void exportsData(ModelMap map, HttpServletRequest request, HttpServletResponse response, @DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        ShiroUser user = ShiroKit.getUser();
        inDto.put("lang", LangUtils.getLang(user.getLANG()));
        inDto.put("GWDBENT", user.getDBC());
        List<Map<String, Object>> list = gwdc002Service.getListData(null, inDto);
        ExportParams params = new ExportParams(null, "渠道价格数据", ExcelType.XSSF);
        //params.setFreezeCol(2);
        map.put(NormalExcelConstants.FILE_NAME, "渠道价格数据");
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, Gwdc002Export.class);
        map.put(NormalExcelConstants.PARAMS, params);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    @RequestMapping(value = "/importsData", method = RequestMethod.POST)
    @RequiresPermissions("crm:gwdc002:init")
    @ResponseBody
    public ResponseData importsData(MultipartFile file, ModelMap map) {
        ShiroUser user = ShiroKit.getUser();
        Dto inDto = Dtos.newDto();
        ImportParams params = new ImportParams();
        params.setTitleRows(0);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数,默认1
        params.setStartRows(0);//字段真正值和列标题之间的距离 默认0
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        int count = 0;
        try {
            List<GwdbT> list = ExcelImportUtil.importExcel(file.getInputStream(), GwdbT.class, params);
            List<String> sList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getGWDB003() != null && list.get(i).getGWDB005() != null) {
                    if (list.get(i).getGWDB003().equals("渠道")) {
                        list.get(i).setGWDB003("1");
                    } else if (list.get(i).getGWDB003().equals("渠道商")) {
                        list.get(i).setGWDB003("2");
                    }
                    sList.add(list.get(i).getGWDB003() + "/" + list.get(i).getGWDB005());
                }
            }
            List<String> listNew = new ArrayList<>(new HashSet(sList));
            for (String a : listNew) {
                List<GwdbT> list3 = new ArrayList<>();
                String list2[] = a.split("/");
                Dto dto = Dtos.newDto();
                for (int i = 0; i < list.size(); i++) {
                    if (list2[0].equals(list.get(i).getGWDB003()) && list2[1].equals(fmt.format(list.get(i).getGWDB005()))) {
                        if (list.get(i).getGWDB012() != null && list.get(i).getGWDB014() != null && list.get(i).getGWDB016() != null) {
                            int day = 0;
                            if (list.get(i).getGWDB006() != null) {
                                day = list.get(i).getGWDB006().compareTo(list.get(i).getGWDB005());
                            }
                            if (list.get(i).getGWDB006() == null) {
                                day = 0;
                            }
                            if (day >= 0) {
                                int gwak = 0;
                                if (list.get(i).getGWDB003().equals("1")) {
                                    QueryWrapper<GwaeT> gwaeTUpdateWrapper = new QueryWrapper<>();
                                    gwaeTUpdateWrapper.eq("GWAEENT", user.getDBC());
                                    gwaeTUpdateWrapper.eq("GWAE001", list.get(i).getGWDB012());
                                    gwaeTUpdateWrapper.eq("GWAEACTI", "Y");
                                    gwak = gwaeTMapper.selectList(gwaeTUpdateWrapper).size();
                                } else {
                                    QueryWrapper<GwakT> gwakTUpdateWrapper = new QueryWrapper<>();
                                    gwakTUpdateWrapper.eq("GWAKENT", user.getDBC());
                                    gwakTUpdateWrapper.eq("GWAK001", list.get(i).getGWDB012());
                                    gwakTUpdateWrapper.eq("GWAKACTI", "Y");
                                    gwak = gwakTMapper.selectList(gwakTUpdateWrapper).size();
                                }
                                QueryWrapper<GwamT> gwamTUpdateWrapper = new QueryWrapper<>();
                                gwamTUpdateWrapper.eq("GWAMENT", user.getDBC());
                                gwamTUpdateWrapper.eq("GWAM001", list.get(i).getGWDB014());
                                gwamTUpdateWrapper.eq("GWAMACTI", "Y");
                                int gwam = gwamTMapper.selectList(gwamTUpdateWrapper).size();
                                if (gwak > 0 && gwam > 0) {
                                    if (list.get(i).getGWDB003().equals("1")) {
                                        Dto gwael = gwdc002Service.getGwael(user.getDBC(), list.get(i).getGWDB012(), LangUtils.getLang(user.getLANG()));
                                        list.get(i).setGWDB013(gwael.getString("GWAEL003"));
                                    } else {
                                        Dto gwakl = gwdc002Service.getGwakl(user.getDBC(), list.get(i).getGWDB012(), LangUtils.getLang(user.getLANG()));
                                        list.get(i).setGWDB013(gwakl.getString("GWAKL004"));
                                    }
                                    List<GwamT> gwamT = gwamTMapper.selectList(gwamTUpdateWrapper);
                                    list.get(i).setGWDB015(gwamT.get(0).getGWAM008());
                                    int j = list.get(i).getGWDB016().compareTo(new BigDecimal(0));
                                    if (j > 0) {
                                        list.get(i).setGWDB016(list.get(i).getGWDB016().setScale(2, BigDecimal.ROUND_HALF_UP));
                                        list3.add(list.get(i));
                                    }
                                } else if (gwak == 0) {
                                    if (list.get(i).getGWDB003().equals("1")) {
                                        return new ErrorResponseData(402,
                                                "对象类型渠道:" + list.get(i).getGWDB012() + "在渠道表中未查询到!");
                                    } else if (list.get(i).getGWDB003().equals("2")) {
                                        return new ErrorResponseData(402,
                                                "对象类型渠道商:" + list.get(i).getGWDB012() + "在客户表中未查询到!");
                                    }
                                } else if (gwam == 0) {
                                    return new ErrorResponseData(402,
                                            "商品:" + list.get(i).getGWDB014() + "在商品表中未查询到!");
                                }
                            }
                        }
                    }
                }
                Date date = new Date();
                String gwdb001 = "QDJG" + DateUtils.formatDate(date, "yyyyMMddHHmmSSS");
                int gwdb002 = 1;
                LocalDateTime GWDB010 = LocalDateTime.now();
                for (GwdbT gwdbT : list3) {
                    Dto sDto = Dtos.newDto();
                    sDto.put("GWDBENT", user.getDBC());
                    sDto.put("GWDB001", gwdb001);
                    sDto.put("GWDB003", gwdbT.getGWDB003());
                    sDto.put("GWDB005", gwdbT.getGWDB005());
                    sDto.put("GWDB012", gwdbT.getGWDB012());
                    sDto.put("GWDB014", gwdbT.getGWDB014());
                    Dto pDto = gwdc002Service.getGwdb(sDto);
                    if (pDto == null) {
                        gwdbT.setGWDB001(gwdb001);
                        gwdbT.setGWDB002(String.valueOf(gwdb002));
                        gwdbT.setGWDBENT(user.getDBC());
                        gwdbT.setGWDB004(LocalDate.now());
                        gwdbT.setGWDB007(user.getID());
                        gwdbT.setGWDB008(user.getORG_ID());
                        gwdbT.setGWDB009(user.getID());
                        //gwdbT.setGWDB010(GWDB010);
                        gwdbT.setGWDBACTI("N");
                        gwdbT.insert();
                        gwdb002++;
                        count++;
                    }
                }
                GwdbT gwdb = new GwdbT();
                gwdb.setGWDBENT(user.getDBC());
                gwdb.setGWDB001(gwdb001);
                //gwdb.setGWDB010(GWDB010);
                gwdb.setGWDBTIME(DateUtils.getTime());
                UpdateWrapper<GwdbT> gwdbTUpdateWrapper = new UpdateWrapper<>();
                gwdbTUpdateWrapper.eq("GWDBENT", user.getDBC());
                gwdbTUpdateWrapper.eq("GWDB001", gwdb001);
                gwdb.update(gwdbTUpdateWrapper);
            }
            if (count == 0) {
                return new ErrorResponseData(401,
                        "所有导入数据都不符合要求!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(),
                    BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        return SUCCESS_TIP;
    }

}
